#include <iostream>
#include <fstream>
#include <string>
#include "addressbook.pb.h"

void WriteAddressBook()
{
    tutorial::AddressBook address_book;

    // 添加一个 Person
    tutorial::Person *person = address_book.add_people();
    person->set_name("Alice");
    person->set_email("alice@example.com");

    // 写入到文件
    std::ofstream output("addressbook.data", std::ios::binary);
    if (!address_book.SerializeToOstream(&output))
    {
        std::cerr << "Failed to write address book." << std::endl;
        return;
    }
}

void ReadAddressBook()
{
    tutorial::AddressBook address_book;

    // 从文件读取
    std::ifstream input("addressbook.data", std::ios::binary);
    if (!address_book.ParseFromIstream(&input))
    {
        std::cerr << "Failed to read address book." << std::endl;
        return;
    }

    // 输出读取到的人名
    for (int i = 0; i < address_book.people_size(); ++i)
    {
        const tutorial::Person &person = address_book.people(i);
        std::cout << "Name: " << person.name() << ", Email: " << person.email() << std::endl;
    }
}

int main()
{
    WriteAddressBook();
    ReadAddressBook();
    return 0;
}